<template>
  <div class="order-list-wrapper">
    <!-- 顶部标题栏 -->
    <header>
      <p>我的订单</p>
      <i class="fa fa-refresh refresh-btn" @click="refreshOrderList" :class="{ 'refreshing': isRefreshing }"></i>
    </header>
    
    <!-- 标签导航栏 -->
    <div class="order-tabs">
      <div 
        v-for="tab in tabs" 
        :key="tab.id"
        :class="['tab-item', { active: activeTab === tab.id }]"
        @click="activeTab = tab.id"
      >
        {{ tab.name }}
        <div class="tab-indicator" v-if="activeTab === tab.id"></div>
      </div>
    </div>
    
    <!-- 可滚动的主内容区域 -->
    <div class="main-content">
      <!-- 加载状态 -->
      <div v-if="isLoading" class="loading">
        <p>正在加载订单信息...</p>
      </div>
      
      <!-- 内容区域 -->
      <div v-else>
        <!-- 全部订单标签页 -->
        <div v-if="activeTab === 'all'" class="tab-content">
          <div v-if="allOrders.length === 0" class="empty-state">
            <p>暂无订单信息</p>
          </div>
          <div v-else>
            <!-- 添加快速评价提示 -->
            <div class="quick-review-tip">
              <i class="fa fa-lightbulb-o tip-icon"></i>
              <p>小技巧：长按"评价"按钮可快速提交5星好评</p>
            </div>
            <div class="order-cards">
              <div 
                v-for="order in allOrders" 
                :key="order.id"
                class="order-card"
              >
                <!-- 卡片头部 -->
                <div class="card-header" @click="navigateToOrderDetail(order)">
                  <div class="restaurant-info">
                    <div class="restaurant-logo" v-if="order.business && order.business.image">
                      <img :src="order.business.image" alt="商家Logo" />
                    </div>
                    <div v-else class="restaurant-logo restaurant-logo-default">
                      <i class="fa fa-cutlery"></i>
                    </div>
                    <span class="restaurant-name">{{ order.business ? order.business.businessName : '未知商家' }}</span>
                  </div>
                  <div class="order-status" :class="getOrderStatusClass(order.orderState)">
                    {{ getOrderStatusText(order.orderState) }}
                  </div>
                </div>

                <!-- 卡片主体 - 商品图片水平滚动区 -->
                <div class="card-body">
                  <!-- 订单摘要信息 -->
                  <div class="order-summary-info">
                    <div class="total-items">
                      <i class="fa fa-shopping-basket"></i>
                      共{{ getOrderItemCount(order) }}件商品
                    </div>
                    <div class="order-price">
                      合计: <span class="price">¥{{ order.orderTotal }}</span>
                    </div>
                  </div>

                  <!-- 商品图片滚动区 -->
                  <div class="food-images-scroll">
                    <div v-if="order.orderDetailets && order.orderDetailets.length > 0" class="food-images-container">
                      <div 
                        v-for="detail in order.orderDetailets" 
                        :key="detail.id"
                        class="food-image-item"
                      >
                        <div class="food-image-wrapper">
                          <img 
                            :src="getFoodImage(detail)" 
                            :alt="detail.food ? detail.food.foodName : '商品图片'"
                            @error="handleImageError($event, detail)"
                          />
                        </div>
                        <div class="food-item-details">
                          <div class="food-name-tag">
                            {{ detail.food && detail.food.foodName ? detail.food.foodName : '未知商品' }}
                          </div>
                          <div class="food-quantity-tag">
                            x {{ detail.quantity }}
                          </div>
                        </div>
                      </div>
                    </div>
                    <div v-else class="no-items">
                      <div class="loading-spinner">
                        <i class="fa fa-refresh fa-spin"></i>
                      </div>
                      <p>加载商品信息中...</p>
                    </div>
                  </div>
                </div>

                <!-- 卡片底部 -->
                <div class="card-footer">
                  <div class="order-time">
                    <i class="fa fa-clock-o"></i>
                    {{ getOrderDateText(order) }}
                  </div>
                  <div class="order-actions">
                    <button v-if="order.orderState === 1" class="action-btn pay-btn" @click="goToPayment(order.id)">
                      <i class="fa fa-credit-card"></i> 去支付
                    </button>
                    <!-- 移除取消订单按钮 -->
                    <button class="action-btn reorder-btn">
                      <i class="fa fa-refresh"></i> 再来一单
                    </button>
                    <!-- 评价按钮 - 根据评价状态显示不同的按钮 -->
                    <button 
                      v-if="order.orderState === 4" 
                      :class="[
                        'action-btn', 
                        order.reviewed ? 'reviewed-btn' : 'review-btn'
                      ]" 
                      @click="order.reviewed ? null : openReviewModal(order)"
                      @contextmenu.prevent="handleLongPressReviewButton(order, $event)"
                      :title="order.reviewed ? '已评价' : '点击评价订单（长按可一键好评）'"
                    >
                      <i class="fa" :class="order.reviewed ? 'fa-check-circle' : 'fa-star'"></i> 
                      {{ order.reviewed ? '已评价' : '评价' }}
                    </button>
                  </div>
                </div>

                <!-- 展开的订单详情 -->
                <div class="order-details" v-if="order.isShowDetailet">
                  <!-- 订单时间信息 -->
                  <div class="detail-section">
                    <div class="detail-title">下单时间：</div>
                    <div class="detail-content">{{ formatDateTime(order.orderDate) }}</div>
                  </div>
                  
                  <!-- 配送地址信息 -->
                  <div class="detail-section">
                    <div class="detail-title">配送地址：</div>
                    <div class="detail-content">
                      <p v-if="order.deliveryAddress && order.deliveryAddress.address">
                        {{ order.deliveryAddress.address }}
                      </p>
                      <p v-else>配送地址未找到</p>
                      <p class="contact-detail" v-if="order.deliveryAddress && order.deliveryAddress.contactName">
                        {{ order.deliveryAddress.contactName }}
                        {{ order.deliveryAddress.contactSex === 1 ? '先生' : '女士' }} 
                        {{ order.deliveryAddress.contactTel || '' }}
                      </p>
                    </div>
                  </div>
                  
                  <!-- 商品明细列表 -->
                  <div class="detail-section">
                    <div class="detail-title">商品明细：</div>
                    <div class="food-items-list">
                      <div 
                        v-for="detail in order.orderDetailets" 
                        :key="detail.id" 
                        class="food-detail-item"
                      >
                        <div class="food-detail-info">
                          <p class="food-name">{{ detail.food ? detail.food.foodName : '商品名称缺失' }}</p>
                          <div class="food-detail-right">
                            <p class="food-quantity">x{{ detail.quantity }}</p>
                            <p class="food-price">¥{{ detail.food ? (detail.food.foodPrice * detail.quantity).toFixed(2) : '0.00' }}</p>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  
                  <!-- 配送费 -->
                  <div class="delivery-fee">
                    <p>配送费</p>
                    <p>¥{{ order.business ? order.business.deliveryPrice : '0.00' }}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 待评价标签页 -->
        <div v-else-if="activeTab === 'toReview'" class="tab-content">
          <div v-if="toReviewOrders.length === 0" class="empty-state">
            <p>暂无待评价订单</p>
          </div>
          <div v-else>
            <!-- 添加快速评价提示 -->
            <div class="quick-review-tip">
              <i class="fa fa-lightbulb-o tip-icon"></i>
              <p>小技巧：长按"评价"按钮可快速提交5星好评</p>
            </div>
            <div class="order-cards">
              <div 
                v-for="order in toReviewOrders" 
                :key="order.id"
                class="order-card"
              >
                <!-- 卡片头部 -->
                <div class="card-header" @click="navigateToOrderDetail(order)">
                  <div class="restaurant-info">
                    <div class="restaurant-logo" v-if="order.business && order.business.image">
                      <img :src="order.business.image" alt="商家Logo" />
                    </div>
                    <div v-else class="restaurant-logo restaurant-logo-default">
                      <i class="fa fa-cutlery"></i>
                    </div>
                    <span class="restaurant-name">{{ order.business ? order.business.businessName : '未知商家' }}</span>
                  </div>
                  <div class="order-status" :class="getOrderStatusClass(order.orderState)">
                    {{ getOrderStatusText(order.orderState) }}
                  </div>
                </div>

                <!-- 卡片主体 - 商品图片水平滚动区 -->
                <div class="card-body">
                  <!-- 订单摘要信息 -->
                  <div class="order-summary-info">
                    <div class="total-items">
                      <i class="fa fa-shopping-basket"></i>
                      共{{ getOrderItemCount(order) }}件商品
                    </div>
                    <div class="order-price">
                      合计: <span class="price">¥{{ order.orderTotal }}</span>
                    </div>
                  </div>

                  <!-- 商品图片滚动区 -->
                  <div class="food-images-scroll">
                    <div v-if="order.orderDetailets && order.orderDetailets.length > 0" class="food-images-container">
                      <div 
                        v-for="detail in order.orderDetailets" 
                        :key="detail.id"
                        class="food-image-item"
                      >
                        <div class="food-image-wrapper">
                          <img 
                            :src="getFoodImage(detail)" 
                            :alt="detail.food ? detail.food.foodName : '商品图片'"
                            @error="handleImageError($event, detail)"
                          />
                        </div>
                        <div class="food-item-details">
                          <div class="food-name-tag">
                            {{ detail.food && detail.food.foodName ? detail.food.foodName : '未知商品' }}
                          </div>
                          <div class="food-quantity-tag">
                            x {{ detail.quantity }}
                          </div>
                        </div>
                      </div>
                    </div>
                    <div v-else class="no-items">
                      <div class="loading-spinner">
                        <i class="fa fa-refresh fa-spin"></i>
                      </div>
                      <p>加载商品信息中...</p>
                    </div>
                  </div>
                </div>

                <!-- 卡片底部 -->
                <div class="card-footer">
                  <div class="order-time">
                    <i class="fa fa-clock-o"></i>
                    {{ getOrderDateText(order) }}
                  </div>
                  <div class="order-actions">
                    <button v-if="order.orderState === 1" class="action-btn pay-btn" @click="goToPayment(order.id)">
                      <i class="fa fa-credit-card"></i> 去支付
                    </button>
                    <!-- 移除取消订单按钮 -->
                    <button class="action-btn reorder-btn">
                      <i class="fa fa-refresh"></i> 再来一单
                    </button>
                    <!-- 评价按钮 - 根据评价状态显示不同的按钮 -->
                    <button 
                      v-if="order.orderState === 4"
                      :class="[
                        'action-btn', 
                        order.reviewed ? 'reviewed-btn' : 'review-btn'
                      ]" 
                      @click="order.reviewed ? null : openReviewModal(order)"
                      @contextmenu.prevent="handleLongPressReviewButton(order, $event)"
                      :title="order.reviewed ? '已评价' : '点击评价订单（长按可一键好评）'"
                    >
                      <i class="fa" :class="order.reviewed ? 'fa-check-circle' : 'fa-star'"></i> 
                      {{ order.reviewed ? '已评价' : '评价' }}
                    </button>
                  </div>
                </div>

                <!-- 展开的订单详情 -->
                <div class="order-details" v-if="order.isShowDetailet">
                  <!-- 订单时间信息 -->
                  <div class="detail-section">
                    <div class="detail-title">下单时间：</div>
                    <div class="detail-content">{{ formatDateTime(order.orderDate) }}</div>
                  </div>
                  
                  <!-- 配送地址信息 -->
                  <div class="detail-section">
                    <div class="detail-title">配送地址：</div>
                    <div class="detail-content">
                      <p v-if="order.deliveryAddress && order.deliveryAddress.address">
                        {{ order.deliveryAddress.address }}
                      </p>
                      <p v-else>配送地址未找到</p>
                      <p class="contact-detail" v-if="order.deliveryAddress && order.deliveryAddress.contactName">
                        {{ order.deliveryAddress.contactName }}
                        {{ order.deliveryAddress.contactSex === 1 ? '先生' : '女士' }} 
                        {{ order.deliveryAddress.contactTel || '' }}
                      </p>
                    </div>
                  </div>
                  
                  <!-- 商品明细列表 -->
                  <div class="detail-section">
                    <div class="detail-title">商品明细：</div>
                    <div class="food-items-list">
                      <div 
                        v-for="detail in order.orderDetailets" 
                        :key="detail.id" 
                        class="food-detail-item"
                      >
                        <div class="food-detail-info">
                          <p class="food-name">{{ detail.food ? detail.food.foodName : '商品名称缺失' }}</p>
                          <div class="food-detail-right">
                            <p class="food-quantity">x{{ detail.quantity }}</p>
                            <p class="food-price">¥{{ detail.food ? (detail.food.foodPrice * detail.quantity).toFixed(2) : '0.00' }}</p>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  
                  <!-- 配送费 -->
                  <div class="delivery-fee">
                    <p>配送费</p>
                    <p>¥{{ order.business ? order.business.deliveryPrice : '0.00' }}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 退款/售后标签页 -->
        <div v-else-if="activeTab === 'refund'" class="tab-content">
          <div class="empty-state">
            <p>暂无退款/售后订单</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部菜单部分 -->
    <Footer></Footer>

    <!-- 评价弹窗 -->
    <ReviewForm
      v-if="showReviewModal"
      :order="currentReviewOrder"
      :is-open="showReviewModal"
      @close="closeReviewModal"
      @success="handleReviewSuccess"
    ></ReviewForm>
  </div>
</template>
  
  <script setup>
  import Footer from "../components/Footer.vue";
  import { useRouter, useRoute } from "vue-router";
  import { ref, onMounted, computed, inject } from "vue";
  import { orderApi } from "../api";
  import ReviewForm from "../components/ReviewForm.vue";

  const router = useRouter();
  const route = useRoute();
  const axios = inject('axios'); // 注入axios实例

  // 从本地存储获取用户信息
  const userInfoStr = localStorage.getItem('user-info');
  let user = null;
  if (userInfoStr) {
    try {
      user = JSON.parse(userInfoStr);
      console.log('获取到用户信息:', user);
    } catch (e) {
      console.error('解析用户信息失败:', e);
    }
  }

  // 标签页数据
  const tabs = [
    { id: 'all', name: '全部订单' },
    { id: 'toReview', name: '待评价' },
    { id: 'refund', name: '退款/售后' }
  ];
  const activeTab = ref('all');

  // 订单数据
  const orderList = ref([]);
  const isLoading = ref(true);
  const isRefreshing = ref(false);

  // 计算属性：全部订单
  const allOrders = computed(() => {
    return orderList.value.map(order => {
      // 为每个订单添加展示详情的标记
      if (order.isShowDetailet === undefined) {
        order.isShowDetailet = false;
      }
      return order;
    });
  });

  // 计算属性：待支付订单
  const unpaidOrders = computed(() => {
    return orderList.value.filter(order => order.orderState === 1);
  });

  // 计算属性：已支付订单
  const paidOrders = computed(() => {
    return orderList.value.filter(order => order.orderState >= 2);
  });

  // 计算属性：待评价订单
  const toReviewOrders = computed(() => {
    console.log("计算待评价订单列表...");
    
    // 过滤已送达但未评价的订单
    const filtered = orderList.value.filter(order => {
      const isEligible = order.orderState === 4 && !order.reviewed;
      console.log(`订单 ${order.id}: 状态=${order.orderState}, 已评价=${order.reviewed}, 是否显示在待评价=${isEligible}`);
      return isEligible;
    });
    
    console.log(`待评价订单数量: ${filtered.length}`);
    return filtered;
  });

  // 添加评价相关的状态
  const showReviewModal = ref(false);
  const currentReviewOrder = ref(null);

  // 打开评价弹窗
  const openReviewModal = (order) => {
    currentReviewOrder.value = order;
    showReviewModal.value = true;
  };

  // 关闭评价弹窗
  const closeReviewModal = () => {
    showReviewModal.value = false;
    currentReviewOrder.value = null;
  };

  // 评价提交成功处理
  const handleReviewSuccess = (reviewData) => {
    console.log('评价提交成功，响应数据:', reviewData);
    
    // 无论响应如何，都标记当前订单为已评价
    if (currentReviewOrder.value) {
      console.log('正在更新订单评价状态，当前评价订单ID:', currentReviewOrder.value.id);
      
      const orderIndex = orderList.value.findIndex(o => o.id === currentReviewOrder.value.id);
      if (orderIndex !== -1) {
        console.log(`找到订单索引: ${orderIndex}, 更新状态为已评价`);
        
        // 强制标记为已评价
        orderList.value[orderIndex].reviewed = true;
        
        // 强制更新视图
        console.log('强制更新视图');
        const updatedOrders = [...orderList.value];
        orderList.value = [];
        setTimeout(() => {
          orderList.value = updatedOrders;
          console.log('视图更新完成');
        }, 0);
      } else {
        console.warn('未找到要更新的订单', currentReviewOrder.value.id);
      }
    }
    
    // 关闭弹窗
    console.log('关闭评价弹窗');
    closeReviewModal();
    
    // 显示成功信息
    alert("评价提交成功！");
  };

  // 初始化数据
  const init = async () => {
    console.log('OrderList页面初始化');
    isLoading.value = true;
    orderList.value = [];
    
    try {
      // 1. 使用API获取订单列表
      console.log('正在获取订单列表...');
      const orders = await orderApi.getOrderList();
      console.log('获取订单列表成功:', orders);
      
      // 2. 获取每个订单的商品详情
      console.log('开始获取所有订单的商品详情...');
      const ordersWithDetails = await Promise.all(
        orders.map(async (order) => {
          // 为每个订单添加isShowDetailet属性和reviewed属性
          const processedOrder = {
            ...order,
            isShowDetailet: false,
            reviewed: false // 默认未评价
          };
          
          try {
            // 获取订单商品详情
            const detailets = await orderApi.getOrderDetailets(order.id);
            console.log(`订单 ${order.id} 商品详情获取成功:`, detailets);
            
            // 调试打印每个商品的详细信息
            if (detailets && detailets.length > 0) {
              detailets.forEach((item, index) => {
                console.log(`商品 ${index + 1} 数据:`, item);
                console.log(`- 食品对象:`, item.food);
                console.log(`- 食品图片URL:`, item.food ? item.food.foodImg : '无');
              });
            }
            
            processedOrder.orderDetailets = detailets;
            
            // 检查订单是否已评价
            try {
              console.log(`正在检查订单 ${order.id} 的评价状态...`);
              const reviewResponse = await axios.get(`/api/reviews/order/${order.id}`);
              console.log(`订单 ${order.id} 评价状态响应:`, reviewResponse);
              
              // 任何非空响应都表示订单已评价
              if (reviewResponse && 
                 ((reviewResponse.data && reviewResponse.data !== null) || 
                  (reviewResponse.id !== undefined))) {
                console.log(`订单 ${order.id} 已评价，标记为reviewed=true`);
                processedOrder.reviewed = true;
              } else {
                console.log(`订单 ${order.id} 未评价，标记为reviewed=false`);
                processedOrder.reviewed = false;
              }
            } catch (reviewError) {
              // 如果获取评价失败，假设订单未评价
              console.log(`订单 ${order.id} 评价状态检查失败:`, reviewError);
              processedOrder.reviewed = false;
            }
            
          } catch (error) {
            console.error(`获取订单 ${order.id} 商品详情失败:`, error);
            processedOrder.orderDetailets = [];
          }
          
          return processedOrder;
        })
      );
      
      orderList.value = ordersWithDetails;
      console.log('所有订单处理完成:', orderList.value);
      
      // 移除临时测试代码
      
      // DEBUG: 打印所有订单的评价状态
      orderList.value.forEach((order) => {
        console.log(`DEBUG: 订单 ${order.id} 最终评价状态: ${order.reviewed ? '已评价' : '未评价'}`);
      });
    } catch (error) {
      console.error('初始化数据失败:', error);
      alert('获取订单列表失败，请稍后重试');
    } finally {
      isLoading.value = false;
    }
  };

  // 初始加载
  onMounted(() => {
    init();
  });

  // 切换订单详情显示状态
  const toggleOrderDetail = (order) => {
    order.isShowDetailet = !order.isShowDetailet;
    
    // 添加调试信息，帮助诊断问题
    if (order.isShowDetailet) {
      console.log('订单详情数据:', {
        id: order.id,
        orderDate: order.orderDate,
        orderState: order.orderState,
        orderTotal: order.orderTotal,
        fullOrderData: order
      });
    }
  };

  // 跳转到支付页面
  const goToPayment = (orderId) => {
    console.log('跳转到支付页面，订单ID:', orderId);
    router.push({ 
      path: '/payment', 
      query: { orderId: orderId } 
    });
  };

  // 跳转到订单详情页面
  const navigateToOrderDetail = (order) => {
    console.log('跳转到订单详情页面，订单ID:', order.id);
    router.push({ 
      path: `/order-details/${order.id}`
    });
  };

  // 获取订单状态文本
  const getOrderStatusText = (orderState) => {
    const statusMap = {
      0: '已取消/已拒绝',
      1: '待支付',
      2: '待接单',
      3: '制作中',
      4: '已送达',
      5: '退款审核中',
      6: '退款成功'
    };
    return statusMap[orderState] || '未知状态';
  };

  // 获取订单状态类名
  const getOrderStatusClass = (orderState) => {
    const classMap = {
      0: 'status-canceled',
      1: 'status-unpaid',
      2: 'status-waiting',
      3: 'status-cooking',
      4: 'status-delivered',
      5: 'status-refunding',
      6: 'status-refunded'
    };
    return classMap[orderState] || '';
  };

  // 获取订单商品总数
  const getOrderItemCount = (order) => {
    if (!order.orderDetailets || !Array.isArray(order.orderDetailets)) {
      return 0;
    }
    
    return order.orderDetailets.reduce((total, item) => {
      return total + (item.quantity || 0);
    }, 0);
  };

  // 刷新订单列表
  const refreshOrderList = () => {
    isRefreshing.value = true;
    init().finally(() => {
      isRefreshing.value = false;
    });
  };

  // 格式化日期时间
  const formatDateTime = (dateTimeStr) => {
    if (!dateTimeStr) return '未知时间';
    
    try {
      const date = new Date(dateTimeStr);
      
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        return dateTimeStr; // 返回原始字符串，如果日期无效
      }
      
      // 格式化为 "YYYY-MM-DD HH:MM:SS" 格式
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    } catch (error) {
      console.error('日期格式化错误:', error);
      return dateTimeStr; // 出错时返回原始字符串
    }
  };

  // 获取订单日期文本
  const getOrderDateText = (order) => {
    if (!order.orderDate) return '下单时间未知';
    try {
      const date = new Date(order.orderDate);
      if (isNaN(date.getTime())) {
        return '下单时间未知';
      }
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `下单: ${month}-${day} ${hours}:${minutes}`;
    } catch (e) {
      return '下单时间未知';
    }
  };

  // 处理食品图片URL
  const getFoodImage = (detail) => {
    // 如果有商品且有图片，则返回图片URL
    if (detail.food && detail.food.foodImg) {
      // 有些foodImg可能是完整的URL，有些可能只是相对路径
      if (detail.food.foodImg.startsWith('http')) {
        return detail.food.foodImg;
      } else {
        // 使用前端中的一些默认食品图片作为替代
        return getDefaultFoodImage(detail.food.foodName);
      }
    } else {
      // 如果没有图片，返回默认图片
      return getDefaultFoodImage(detail.food ? detail.food.foodName : '');
    }
  };

  // 处理图片加载失败
  const handleImageError = (event, detail) => {
    console.warn(`图片加载失败: ${detail.food ? detail.food.foodName : '未知商品'}`, event.target.src);
    // 替换为默认图片
    event.target.src = getDefaultFoodImage(detail.food ? detail.food.foodName : '');
  };

  // 根据食品名称返回默认图片
  const getDefaultFoodImage = (foodName = '') => {
    // 根据名称首字母或关键词选择默认图片
    const foodNameLower = foodName.toLowerCase();
    
    if (foodNameLower.includes('汉堡') || foodNameLower.includes('burger')) {
      return '/src/assets/sp01.png';
    } else if (foodNameLower.includes('披萨') || foodNameLower.includes('pizza')) {
      return '/src/assets/sp02.png';
    } else if (foodNameLower.includes('炸鸡') || foodNameLower.includes('chicken')) {
      return '/src/assets/sp03.png';
    } else if (foodNameLower.includes('冰淇淋') || foodNameLower.includes('ice cream')) {
      return '/src/assets/sp04.png';
    } else if (foodNameLower.includes('沙拉') || foodNameLower.includes('salad')) {
      return '/src/assets/sp05.png';
    } else if (foodNameLower.includes('蛋糕') || foodNameLower.includes('cake')) {
      return '/src/assets/sp06.png';
    } else if (foodNameLower.includes('咖啡') || foodNameLower.includes('coffee')) {
      return '/src/assets/sp07.png';
    } else if (foodNameLower.includes('奶茶') || foodNameLower.includes('tea')) {
      return '/src/assets/sp08.png';
    } else {
      // 默认图片，根据字符串的哈希值选择一个
      const images = [
        '/src/assets/sp09.png', 
        '/src/assets/sp10.png', 
        '/src/assets/sp11.png', 
        '/src/assets/sp12.png'
      ];
      
      // 简单哈希函数，将字符串映射到图片数组索引
      const hash = foodName.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0) % images.length;
      return images[hash];
    }
  };

  // 添加调试方法 - 手动切换订单评价状态
  const toggleReviewedStatus = (order) => {
    console.log(`手动切换订单 ${order.id} 的评价状态，当前状态: ${order.reviewed}`);
    order.reviewed = !order.reviewed;
    console.log(`切换后状态: ${order.reviewed}`);
    
    // 强制更新视图
    orderList.value = [...orderList.value];
  };

  // 自动提交默认评价
  const submitDefaultReview = async (order) => {
    console.log(`自动提交订单 ${order.id} 的默认5星好评...`);
    
    try {
      // 准备默认评价数据
      const defaultReviewData = {
        orderId: order.id,
        businessId: order.business?.id,
        rating: 5, // 默认5星好评
        content: "购买体验非常好，商家态度很热情，下次还会再点这家",
        isAnonymous: false
      };
      
      console.log('提交默认评价数据:', defaultReviewData);
      
      // 发送评价请求
      const response = await axios.post('/api/reviews', defaultReviewData);
      
      // 处理成功响应
      console.log('默认评价提交成功:', response);
      
      // 更新订单评价状态
      order.reviewed = true;
      
      // 强制更新视图
      orderList.value = [...orderList.value];
      
      // 显示成功消息
      alert("已为您提交默认5星好评！");
      
    } catch (error) {
      console.error('默认评价提交失败:', error);
      alert(`默认评价提交失败: ${error.response?.data?.message || error.message || '请稍后重试'}`);
    }
  };

  // 在订单卡片底部添加长按事件处理，长按评价按钮提交默认评价
  const handleLongPressReviewButton = (order, event) => {
    console.log('长按评价按钮...');
    event.preventDefault();
    
    // 如果已经评价过，则切换回未评价状态(仅用于调试)
    if (order.reviewed) {
      toggleReviewedStatus(order);
      return;
    }
    
    // 如果未评价，则自动提交默认评价
    submitDefaultReview(order);
  };

  // 取消订单
  const cancelOrder = async (orderId) => {
    if (!confirm('确定要取消此订单吗？')) {
      return;
    }
    
    try {
      console.log(`取消订单: ${orderId}`);
      await orderApi.cancelOrder(orderId);
      
      // 更新本地订单状态
      const orderIndex = orderList.value.findIndex(o => o.id === orderId);
      if (orderIndex !== -1) {
        orderList.value[orderIndex].orderState = 0;
        // 强制更新视图
        orderList.value = [...orderList.value];
        console.log(`订单 ${orderId} 已取消`);
      }
      
      alert('订单已成功取消');
    } catch (error) {
      console.error(`取消订单失败: ${error}`);
      alert(`取消订单失败: ${error.message || '请稍后重试'}`);
    }
  };
  </script>
  
  <style scoped>
/****************** 总容器 ******************/
.order-list-wrapper {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: #f5f5f5;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
}

/****************** 主内容区域 ******************/
.main-content {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding-bottom: 20vw; /* 为底部Footer预留空间 */
  -webkit-overflow-scrolling: touch; /* iOS 平滑滚动 */
  scroll-behavior: smooth; /* 平滑滚动 */
}

/* 滚动条样式优化 */
.main-content::-webkit-scrollbar {
  width: 2px;
}

.main-content::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.main-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 1px;
}

.main-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/****************** 加载状态 ******************/
.loading {
  width: 100%;
  margin-top: 15vw; /* 为header预留空间 */
  padding: 10vw;
  text-align: center;
  color: #666;
  font-size: 4vw;
}

/****************** 空状态 ******************/
.empty-state {
  width: 100%;
  padding: 15vw 4vw;
  text-align: center;
  color: #999;
  font-size: 3.8vw;
  background-color: #f9f9f9;
  margin: 2vw 0;
  border-radius: 8px;
}

/****************** header部分 ******************/
.order-list-wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097ff;
  color: #fff;
  font-size: 4.8vw;
  font-weight: 500;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  z-index: 1000;
}

.order-list-wrapper header .refresh-btn {
  position: absolute;
  right: 4vw;
  font-size: 4vw;
  cursor: pointer;
  transition: all 0.3s ease;
  padding: 2vw;
}

.order-list-wrapper header .refresh-btn:hover {
  opacity: 0.8;
}

.order-list-wrapper header .refresh-btn.refreshing {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/****************** 标签页导航 ******************/
.order-tabs {
  width: 100%;
  display: flex;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  padding: 0 2vw;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  z-index: 900;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 3vw 0;
  font-size: 3.8vw;
  color: #666;
  position: relative;
  transition: all 0.3s ease;
  cursor: pointer;
}

.tab-item.active {
  color: #0097ff;
  font-weight: 600;
}

.tab-indicator {
  position: absolute;
  bottom: 0;
  left: 25%;
  width: 50%;
  height: 0.6vw;
  background-color: #0097ff;
  border-radius: 1vw 1vw 0 0;
  transition: all 0.3s ease;
}

.tab-content {
  padding: 3vw;
}

/****************** 订单卡片 ******************/
.order-cards {
  display: flex;
  flex-direction: column;
  gap: 3vw;
}

.order-card {
  background-color: #fff;
  border-radius: 2vw;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 3vw;
}

/* 卡片头部 */
.card-header {
  padding: 3vw;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f1f1f1;
  cursor: pointer;
}

.restaurant-info {
  display: flex;
  align-items: center;
  gap: 2vw;
}

.restaurant-logo {
  width: 10vw;
  height: 10vw;
  border-radius: 50%;
  overflow: hidden;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.restaurant-logo img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.restaurant-name {
  font-size: 4vw;
  font-weight: 600;
  color: #333;
}

.order-status {
  padding: 1vw 2vw;
  border-radius: 1vw;
  font-size: 3.2vw;
  font-weight: 500;
  color: #fff;
}

.status-unpaid {
  background-color: #ff9800;
}

.status-paid {
  background-color: #4caf50;
}

.status-delivering {
  background-color: #2196f3;
}

.status-delivered {
  background-color: #8bc34a;
}

.status-canceled {
  background-color: #9e9e9e;
}

.status-refunded {
  background-color: #8bc34a;
}

.status-refunding {
  background-color: #ff9800;
}

/* 卡片主体 - 商品图片水平滚动区 */
.card-body {
  padding: 3vw;
  border-bottom: 1px solid #f1f1f1;
}

.order-summary-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2vw;
  padding-bottom: 2vw;
  border-bottom: 1px solid #eee;
}

.total-items {
  display: flex;
  align-items: center;
  gap: 1vw;
  font-size: 3.5vw;
  color: #666;
}

.total-items i {
  font-size: 4vw;
  color: #0097ff;
}

.order-price {
  font-size: 3.8vw;
  color: #ff6b35;
  font-weight: 600;
}

.price {
  font-size: 3.8vw;
  color: #ff6b35;
  font-weight: 600;
}

.food-images-scroll {
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  scroll-behavior: smooth;
  padding: 1vw 0;
}

/* 隐藏水平滚动条 */
.food-images-scroll::-webkit-scrollbar {
  display: none;
}

.food-images-container {
  display: flex;
  gap: 2vw;
  padding: 1vw;
}

.food-image-item {
  min-width: 18vw;
  max-width: 25vw;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 1vw;
}

.food-image-wrapper {
  width: 100%;
  height: 18vw;
  border-radius: 1.5vw;
  overflow: hidden;
  background-color: #f5f5f5;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.food-image-item .food-image-wrapper {
  width: 100%;
  height: 18vw;
  border-radius: 1.5vw;
  overflow: hidden;
  background-color: #f5f5f5;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.food-image-item .food-image-wrapper img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.food-item-details {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  margin-top: 1vw;
}

.food-name-tag {
  font-size: 3vw;
  color: #666;
  text-align: center;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.food-quantity-tag {
  font-size: 3vw;
  color: #999;
  margin-top: 0.5vw;
}

.food-image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 8vw;
  background-color: #ffab40;
  font-weight: bold;
}

.no-items {
  padding: 3vw;
  text-align: center;
  color: #999;
  font-size: 3.5vw;
}

.loading-spinner {
  margin-bottom: 1vw;
}

.loading-spinner i {
  font-size: 5vw;
  color: #0097ff;
  animation: spin 1s linear infinite;
}

/* 卡片底部 */
.card-footer {
  padding: 3vw;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-time {
  font-size: 3.5vw;
  color: #666;
  display: flex;
  align-items: center;
  gap: 1vw;
}

.order-time i {
  font-size: 4vw;
  color: #0097ff;
}

.order-actions {
  display: flex;
  gap: 2vw;
}

.action-btn {
  padding: 1.5vw 3vw;
  border-radius: 5vw;
  font-size: 3.4vw;
  font-weight: 500;
  border: none;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5vw;
}

.pay-btn {
  background-color: #ff9800;
  color: #fff;
}

.pay-btn:hover {
  background-color: #f57c00;
}

.reorder-btn {
  background-color: #ffeb3b;
  color: #333;
}

.reorder-btn:hover {
  background-color: #fdd835;
}

.review-btn {
  background-color: #4caf50;
  color: #fff;
}

.review-btn:hover {
  background-color: #388e3c;
}

.cancel-btn {
  background-color: #f44336;
  color: #fff;
}

.cancel-btn:hover {
  background-color: #d32f2f;
}

/* 展开的订单详情 */
.order-details {
  padding: 3vw;
  background-color: #f9f9f9;
  border-top: 1px solid #eee;
}

.detail-section {
  margin-bottom: 3vw;
}

.detail-title {
  font-size: 3.5vw;
  font-weight: 600;
  color: #666;
  margin-bottom: 1vw;
}

.detail-content {
  font-size: 3.5vw;
  color: #333;
  line-height: 1.4;
}

.contact-detail {
  font-size: 3.2vw;
  color: #666;
  margin-top: 1vw;
}

.food-items-list {
  margin-top: 2vw;
}

.food-detail-item {
  padding: 2vw 0;
  border-bottom: 1px solid #eee;
}

.food-detail-item:last-child {
  border-bottom: none;
}

.food-detail-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.food-name {
  font-size: 3.5vw;
  color: #333;
  max-width: 50vw;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.food-detail-right {
  display: flex;
  align-items: center;
  gap: 3vw;
}

.food-quantity {
  font-size: 3.2vw;
  color: #666;
}

.food-price {
  font-size: 3.5vw;
  color: #ff6b35;
  font-weight: 600;
}

.delivery-fee {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 3vw 0;
  border-top: 1px solid #eee;
  margin-top: 2vw;
  font-size: 3.5vw;
  color: #666;
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.order-card {
  animation: fadeIn 0.3s ease-in-out;
}

.order-total-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2vw;
  padding-bottom: 2vw;
  border-bottom: 1px solid #eee;
}

.order-total .label,
.delivery-fee-info .label {
  font-size: 3.5vw;
  color: #666;
  font-weight: 500;
}

.order-total .value,
.delivery-fee-info .value {
  font-size: 3.8vw;
  color: #ff6b35;
  font-weight: 600;
  margin-left: 1vw;
}

.reviewed-btn {
  background-color: #8bc34a;
  color: #fff;
  cursor: default;
  opacity: 0.8;
}

.reviewed-btn:hover {
  background-color: #8bc34a;
}

/* 快速评价提示 */
.quick-review-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 2vw;
  padding: 2vw 4vw;
  background-color: #e0f2f7;
  border-radius: 1vw;
  border: 1px solid #c6e4ef;
  color: #007bff;
  font-size: 3.2vw;
  font-weight: 500;
}

.quick-review-tip .tip-icon {
  font-size: 4vw;
  margin-right: 1vw;
  color: #007bff;
}
  </style>